package com.fx.controller;

import com.dto.config.IniDTO;
import com.dto.sftp.ReaderIni;
import com.fx.jfxsupport.FXMLController;
import com.sftpserver.RunServer;
import com.sftpserver.TestService;
import com.utils.DiskSpaceUtil;
import com.utils.IniWriter;
import com.utils.PathUtil;
import com.utils.SftpServerUtils;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.function.Consumer;

import static com.fx.notify.NotifyTest.doNotify;

@Slf4j(topic = "界面操作类")
@FXMLController
public class SftpController   implements Initializable,
        ApplicationContextAware, /*CommandLineRunner,*/
        Consumer<Stage> {




    public Button exit;

    public TextField port_Info;
    public TextField path_info;
    public TextField username_info;
    public TextField password_info;
    public TextField ip_info;


    //开始sftp
    public ToggleButton open;


    //public  Label zhuangtai;
    public ToggleButton stop_btn;
    public ProgressBar jindu;
    public Circle led;
    public TextField note;
    public CheckBox run_with_sys;
    public Label disk_check;
//    public Label detailsLabel31;

    private Task<?> task = null;
    private static Consumer<Stage> springStartMain;

    @Override
    public void accept(Stage stage) {

        Button winhide = new Button("隐藏");
        HBox hBox = new HBox();
        hBox.setSpacing(10); //HBox中每个孩子之间的水平距离
        hBox.setAlignment(Pos.CENTER); //所有孩子整体在hBox中的位置居中
//		Button btEnlarge = new Button("Enlarge");
//		Button btShrink = new Button("Shrink");
//		hBox.getChildren().addAll(btEnlarge, btShrink);
        winhide.setLayoutX(300.0);
        winhide.setLayoutY(86.0);
        winhide.setPrefHeight(31.0);
        winhide.setPrefWidth(92.0);
        winhide.setMnemonicParsing(true);
        // 事件处理器对象 listener
        // 在事件源对象注册 source.setOnXEventType(listener)
        // 匿名内部类
        winhide.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                Platform.runLater(stage::close);
            }
        });
        springStartMain.accept(stage);
    }


    public SftpController() {
        this.task = task;
        /*叉掉窗口后仍运行 参数为 false*/
        Platform.setImplicitExit(false);
    }


    /*生命周期——初始化——只有一次*/
    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
//		arg0 == /jasonsang/Desktop/springboot-javaFX-master/target/classes/view/Application.fxml
        //动态读取配置文件

        /*当前版本*/
//        detailsLabel31.setText("当前版本");

        /**
         * [config]
         * --sftp.host=172.19.20.26
         * --sftp.path=C:\
         */
        ip_info.setText(IniDTO.getSftp_host());
        username_info.setText(IniDTO.getSftp_username());
        password_info.setText(IniDTO.getSftp_password());
        path_info.setText(IniDTO.getSftp_path());
        port_Info.setText(IniDTO.getSftp_port());
        //锁信息
        ip_info.setDisable(true);
        username_info.setDisable(true);
        password_info.setDisable(true);
        path_info.setDisable(true);
        port_Info.setDisable(true);
        //System.out.println("当前进程状态:"+service1.getState());
        open.setText("已启动");
        open.setSelected(true);
        // zhuangtai.setText("状态：正常");
        led.setFill(Paint.valueOf("green"));
        /*检查当前磁盘容量*/
        disk_check.setText(new String(new DiskSpaceUtil().testDisk(IniDTO.getSftp_path())));
    }




    /**
     * ScheduledService使用它来取消处于READY状态的服务。 问题是
     * * ScheduledService将从SUCCEEDED迭代到READY，然后调用start（）进行过渡
     * *从READY到SCHEDULED并开始新的迭代。 但是，如果来自SUCCEEDED事件处理程序
     * *开发人员调用“取消”以停止ScheduledService，我们遇到了问题，因为该服务
     * *规范不允许从终端状态（SUCCEEDED）转换到另一个终端
     * *状态（已取消），但这显然是我们需要做的。 因此，此方法将允许
     * *通过通过SCHEDULED进行转换，我们可以从READY状态转换为CANCELED状态
     */

    Service<Void> service1 = new Service<Void>() {

        @SneakyThrows
        @Override
        protected Task<Void> createTask() {

//            //sftpServerApplication.ReaderIni();
//            ip.setText("" + SftpServerApplication.host);
//            user.setText("" + SftpServerApplication.username);
//            password.setText("" + SftpServerApplication.password);
//            catlog.setText("" + SftpServerApplication.path);

            //SftpServerApplication sftpServerApplication = new SftpServerApplication();
            //sftpServerApplication.ReaderIni();

            IniWriter.setProfileString(/*path*/ReaderIni.filePath,
                    "config",
                    "--sftp.username",
                    username_info.getText());

            IniWriter.setProfileString(/*path*/ReaderIni.filePath,
                    "config",
                    "--sftp.password",
                    password_info.getText());

            IniWriter.setProfileString(/*path*/ReaderIni.filePath,
                    "config",
                    "--sftp.port",
                    port_Info.getText());

            IniWriter.setProfileString(/*path*/ReaderIni.filePath,
                    "config",
                    "--sftp.path",
                    path_info.getText());

            IniWriter.setProfileString(/*path*/ReaderIni.filePath,
                    "config",
                    "--sftp.host",
                    ip_info.getText());



            //锁信息
            ip_info.setDisable(true);
            username_info.setDisable(true);
            password_info.setDisable(true);
            path_info.setDisable(true);
            port_Info.setDisable(true);


            open.setText("已启动");
            open.setSelected(true);
            // zhuangtai.setText("状态：已启动");
            stop_btn.setText("暂停");
            stop_btn.setSelected(false);
            /*检查当前磁盘容量*/
            disk_check.setText(new String(new DiskSpaceUtil().testDisk(IniDTO.getSftp_path())));

            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {

//                    Method method = SftpServerApplication.class.getMethod("main", String[].class);
//                    method.invoke(null, (Object)new String[]{new StringBuffer().toString()});
//                    //  Keep with the background work
//                    method.getModifiers();




                    //启动服务
                    try {
                        IniDTO.setSftp_username(username_info.getText());
                        IniDTO.setSftp_password(password_info.getText());
                        IniDTO.setSftp_host(ip_info.getText());
                        IniDTO.setSftp_path(path_info.getText());
                        IniDTO.setSftp_port(port_Info.getText());
                        String username = IniDTO.getSftp_username() ;
                        String password = IniDTO.getSftp_password();
                        String host =  IniDTO.getSftp_host();
                        String path = IniDTO.getSftp_path();
                        String port = IniDTO.getSftp_port() ;

//                        //检查端口占用
                        new TestService(port);
//                        testPort(port_Info.getText());
                        RunServer.serverBean = SftpServerUtils.setupSftpServer(username, password, host, Integer.parseInt(port), path);

                    } catch (Throwable throwable) {
                        //启动中断
                        led.setFill(Paint.valueOf("red"));
                        log.error("重新启动失败");
                    }

                    return null;
                }
            };

        }
    };




    Service<Void> service2 = new Service<Void>() {
        @SneakyThrows
        @Override
        protected Task<Void> createTask() {

            //解锁信息
            ip_info.setDisable(false);
            username_info.setDisable(false);
            password_info.setDisable(false);
            path_info.setDisable(false);
            port_Info.setDisable(false);

            led.setFill(Paint.valueOf("#b8b8b8"));
            // zhuangtai.setText("状态：已暂停");
            stop_btn.setText("已暂停");
            stop_btn.setSelected(true);
            open.setText("启动");
            open.setSelected(false);
            System.out.println("当前进程状态:"+service2.getState());
            // KillServer.killPort(IniDTO.getPort());
            return new Task<Void>() {
                @Override
                protected Void call() throws Exception {


                    //关闭服务
                    SftpServerUtils.stopServer(RunServer.serverBean);
//                    ShutDownConfig.getTerminateBean().init();



                    return null;
                }
            };
        }
    };

    Service<Void> service3 = new Service<Void>() {
        @SneakyThrows
        @Override
        protected Task<Void> createTask() {
            System.out.println("当前进程状态:" + service3.getState());

            return new Task<Void>() {

                @Override
                protected Void call()  {
                    // doNotify("警告","服务启动失败","dialog-information.png");
                    return null;
                }
            };
        }
    };

    Service<Void> service4 = new Service<Void>() {
        @Override
        protected Task<Void> createTask() {
            System.out.println("当前进程状态:" + service4.getState());

            return new Task<Void>() {

                @Override
                protected Void call()  {
                    doNotify("提示","已打开随系统启动","dialog-information.png");
                    return null;
                }
            };
        }
    };


    /**
     * 监控注册表修改进程——开机自动启动
     *
     * @param actionEvent
     * @throws Exception
     */
    public void ac_run_with_sys(ActionEvent actionEvent) {

//        WindowsRegistry reg = WindowsRegistry.getInstance();
        String branch = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";

        if (run_with_sys.isSelected()){
            log.info("打开了自动随系统启动");
//            if (service4.getState() == Worker.State.READY){
////                service4.start();
//            }
            try {
                System.out.println("PathUtil.getExePath():获取的路径是 " + PathUtil.getExePath());
                System.out.println("新增");
//                reg.writeStringValue(HKey.HKCU, branch, "wise-sftp", PathUtil.getExePath() + "\\wise-sftp.exe");
            }catch (Throwable e) {
                log.error(Thread.currentThread().getStackTrace()[1].getMethodName() +"发生的异常是: ",e);
            }




        } else {
            log.info("关闭了自动随系统启动");

            try {
                System.out.println("PathUtil.getExePath():获取的路径是 " + PathUtil.getExePath());
                System.out.println("关闭");

//                reg.writeStringValue(HKey.HKCU, branch, "wise-sftp", "");
            }catch (Throwable e) {
                log.error(Thread.currentThread().getStackTrace()[1].getMethodName() +"发生的异常是: ",e);
            }
        }




    }




    /**
     * 开始服务
     * @param actionEvent
     * @throws Exception
     */
    public void open(ActionEvent actionEvent) throws Exception {
        service2.cancel();
        service1.restart();
//        led.setFill(javafx.scene.paint.Paint.valueOf("#116fff"));
//        zhuangtai.setText("状态：正常");
        led.setFill(Paint.valueOf("green"));



    }

    /**
     * 停止SFTP
     *
     * @param actionEvent
     * @throws IOException
     */
    public void stop(ActionEvent actionEvent) throws IOException {
        service1.cancel();
        service2.restart();
    }


    /**
     * 退出
     *
     * @param actionEvent
     */
    public void exit(ActionEvent actionEvent) {
        Platform.runLater(() -> System.exit(1));
    }

    /**
     * 显示版本信息
     *
     * @param actionEvent
     * @throws IOException
     */
    public void sftp_info(ActionEvent actionEvent) throws IOException {

        Parent root = FXMLLoader.load(getClass().getResource("/view/sftp_info.fxml"));
        Scene scene = new Scene(root);
        Stage stage = new Stage();
        stage.getIcons().add(new Image(getClass().getResource("/icons/wise_16X16.png").toExternalForm()));

        stage.setTitle("版本信息");
        stage.setScene(scene);
        System.out.println("版本信息");
        stage.show();
    }








    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContext context = applicationContext;
    }


    public void doNote(ActionEvent actionEvent) {
    }


}
